/*
package com.rankeiot.ai.util;

import cn.hutool.core.date.StopWatch;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.agentsflex.client.BaseLlmClientListener;
import com.agentsflex.client.LlmClient;
import com.agentsflex.client.LlmClientListener;
import com.agentsflex.client.impl.SseClient;
import com.agentsflex.client.impl.WebSocketClient;
import com.agentsflex.llm.ChatListener;
import com.agentsflex.llm.Llm;
import com.agentsflex.llm.openai.OpenAiLLmUtil;
import com.agentsflex.llm.openai.OpenAiLlm;
import com.agentsflex.llm.openai.OpenAiLlmConfig;
import com.agentsflex.llm.spark.SparkLlm;
import com.agentsflex.llm.spark.SparkLlmConfig;
import com.agentsflex.llm.spark.SparkLlmUtil;
import com.agentsflex.message.AiMessage;
import com.agentsflex.message.FunctionMessage;
import com.agentsflex.message.HumanMessage;
import com.agentsflex.message.SystemMessage;
import com.agentsflex.prompt.HistoriesPrompt;
import com.agentsflex.prompt.SimplePrompt;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rankeiot.core.Current;
import com.rankeiot.core.util.JSONUtil;

import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.entity.chat.*;
import com.unfbx.chatgpt.sse.ConsoleEventSourceListener;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class AIUtil {
    private static final String BASE_URL = "https://api.openai.rankeiot.com/v1";//"http://oneapi.rankeiot.com/v1/";
    //chat/completions
    private static String apiKey = "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";//"sk-7MfJYI5SlILGgSq27a17F5C8EdC54e0a97EcF07aC12025B2";
    private static String model = "gpt-3.5-turbo";
    //"Embedding-V1"
    private static String embeddingModel = "text-embedding-ada-002";

    public static void sparkCall() {
        StopWatch sw = new StopWatch();
        sw.start("chatGpt");
        SparkLlmConfig config = new SparkLlmConfig();
        config.setAppId("f2d01461");
        config.setApiKey("f19f37d2df37fb4d05b11015a8ed86a7");
        config.setApiSecret("NWUxNzBhYjIxYjRlMDljZmZjZTM4MGQw");

        Llm llm = new SparkLlm(config);
        HistoriesPrompt prompt = new HistoriesPrompt();

        AiMessage aiMessage = new AiMessage();
        aiMessage.setFullContent("当前时间是2024年1月30号,你是一个管理系统的助手,通过提供的功能调用获取信息，如果没有获取到信息，则回复\"我不知道\"");
        prompt.addMessage(aiMessage);
        prompt.addMessage(new HumanMessage("下个月24号成都天气如何？"));

//        LlmClient client = llm.chat(prompt,(_llm,msg)->{
//
//            System.out.println(">>>> " + msg.getContent());
//        });

        ChatListener listener = (_llm, msg) -> {
            sw.stop();
            System.out.println(sw.prettyPrint(TimeUnit.MILLISECONDS));
            System.out.println(msg);
        };
        LlmClient llmClient = new WebSocketClient();
        String url = SparkLlmUtil.createURL(config);
        String payload = SparkLlmUtil.promptToPayload(prompt, config);
        JSONObject jo = cn.hutool.json.JSONUtil.parseObj(payload);
        jo.getJSONObject("payload")
                .set("functions"
                        , cn.hutool.json.JSONUtil.parseObj("{\"text\":" +
                                "[{\"name\":\"天气查询\",\"description\":\"根据日期获取所在城市的天气信息\",\"parameters\":{" +
                                "\"type\":\"object\"," +
                                "\"properties\":{\"location\":{\"type\":\"string\",\"description\":\"地点，比如北京市。\"},\"date\":{\"type\":\"string\",\"description\":\"时间，格式为yyyy-MM-dd,如：2012-01-02。\"}}," +
                                "\"required\":[\"location\",\"date\"]}}]" +
                                "}")
                );
        String np=cn.hutool.json.JSONUtil.toJsonStr(jo);
          LlmClientListener clientListener = new BaseLlmClientListener(llm, listener, prompt, SparkLlmUtil::parseAiMessage);


         llmClient.start(url, (Map)null, np, clientListener);

        // client.sendMessage("你好");
    }

    public static void chatFunction() {
        OpenAiClient openAiClient = OpenAiClient.builder()
                .apiKey(Arrays.asList(apiKey))
                //自定义key的获取策略：默认KeyRandomStrategy
                //.keyStrategy(new KeyRandomStrategy())
                // .keyStrategy(new FirstKeyStrategy())
                //自己做了代理就传代理地址，没有可不不传
                .apiHost("https://api.openai.rankeiot.com/")//("http://oneapi.rankeiot.com/")
                .build();
        //模型：GPT_3_5_TURBO_16K_0613
        Message message = Message.builder().role(Message.Role.USER).content("给我输出一个长度为2的中文词语，并解释下词语对应物品的用途").build();
        //属性一
        JSONObject wordLength = new JSONObject();
        wordLength.putOpt("type", "number");
        wordLength.putOpt("description", "词语的长度");
        //属性二
        JSONObject language = new JSONObject();
        language.putOpt("type", "string");
        language.putOpt("enum", Arrays.asList("zh", "en"));
        language.putOpt("description", "语言类型，例如：zh代表中文、en代表英语");
        //参数
        JSONObject properties = new JSONObject();
        properties.putOpt("wordLength", wordLength);
        properties.putOpt("language", language);
        Parameters parameters = Parameters.builder()
                .type("object")
                .properties(properties)
                .required(Arrays.asList("wordLength")).build();
        Functions functions = Functions.builder()
                .name("getOneWord")
                .description("获取一个指定长度和语言类型的词语")
                .parameters(parameters)
                .build();

        ChatCompletion chatCompletion = ChatCompletion
                .builder()
                .messages(Arrays.asList(message))
                .functions(Arrays.asList(functions))
                .functionCall("auto")
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .build();
        ChatCompletionResponse chatCompletionResponse = openAiClient.chatCompletion(chatCompletion);

        ChatChoice chatChoice = chatCompletionResponse.getChoices().get(0);
        System.out.println(chatChoice);
//        log.info("构造的方法值：{}", chatChoice.getMessage().getFunctionCall());
//        log.info("构造的方法名称：{}", chatChoice.getMessage().getFunctionCall().getName());
//        log.info("构造的方法参数：{}", chatChoice.getMessage().getFunctionCall().getArguments());
//        WordParam wordParam = JSONUtil.toBean(chatChoice.getMessage().getFunctionCall().getArguments(), WordParam.class);
//        String oneWord = getOneWord(wordParam);
//
//        FunctionCall functionCall = FunctionCall.builder()
//                .arguments(chatChoice.getMessage().getFunctionCall().getArguments())
//                .name("getOneWord")
//                .build();
//        Message message2 = Message.builder().role(Message.Role.ASSISTANT).content("方法参数").functionCall(functionCall).build();
//        String content
//                = "{ " +
//                "\"wordLength\": \"3\", " +
//                "\"language\": \"zh\", " +
//                "\"word\": \"" + oneWord + "\"," +
//                "\"用途\": [\"直接吃\", \"做沙拉\", \"售卖\"]" +
//                "}";
//        Message message3 = Message.builder().role(Message.Role.FUNCTION).name("getOneWord").content(content).build();
//        List<Message> messageList = Arrays.asList(message, message2, message3);
//        ChatCompletion chatCompletionV2 = ChatCompletion
//                .builder()
//                .messages(messageList)
//                .model(ChatCompletion.Model.GPT_3_5_TURBO_16K_0613.getName())
//                .build();
//        ChatCompletionResponse chatCompletionResponseV2 = openAiClient.chatCompletion(chatCompletionV2);
        //log.info("自定义的方法返回值：{}",chatCompletionResponseV2.getChoices().get(0).getMessage().getContent());
    }

    public static void main(String[] args) throws FileNotFoundException {
        StopWatch sw = new StopWatch();
        sw.start("chatGpt");
//        //  chatFunction();
//        sw.stop();
//        sw.start("spark");
 //       sparkCall();
//        sw.stop();
//        sw.start("gpt 1");
    main1(args);
        sw.stop();
        System.out.println(sw.prettyPrint(TimeUnit.MILLISECONDS));
        // sparkCall();
    }

    public static void main1(String[] args) throws FileNotFoundException {
        //text-embedding-ada-002

        // System.out.println(embedding("控制物联网设备开关"));
        //  speech("你好，我是一个机器人，有什么可以帮助你的吗？");


//        CompletionRequest completionRequest = CompletionRequest.builder()
//                .prompt("Somebody once told me the world is gonna roll me")
//                .model("gpt-3.5-turbo")
//                .echo(true)
//                .build();
//        service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
        OpenAiClient client = OpenAiClient.builder()
                .apiKey(Arrays.asList(apiKey))
                //自定义key的获取策略：默认KeyRandomStrategy
                //.keyStrategy(new KeyRandomStrategy())
                // .keyStrategy(new FirstKeyStrategy())
                //自己做了代理就传代理地址，没有可不不传
                .apiHost("https://api.openai.rankeiot.com/")//("http://oneapi.rankeiot.com/")
                .build();


//        WeatherPlugin plugin = new WeatherPlugin(WeatherReq.class);
//        plugin.setName("知心天气");
//        plugin.setFunction("getLocationWeather");
//        plugin.setDescription("提供一个地址，方法将会获取该地址的天气的实时温度信息。");
//        PluginAbstract.Arg arg = new PluginAbstract.Arg();
//        arg.setName("location");
//        arg.setDescription("地名");
//        arg.setType("string");
//        arg.setRequired(true);
//        plugin.setArgs(Collections.singletonList(arg));


        //聊天模型：gpt-3.5
        // ConsoleEventSourceListener eventSourceListener = new ConsoleEventSourceListener();
        Message sysMessage = Message.builder().role(Message.Role.USER).content("当前时间是2024年1月30号，你是一个管理系统的助手,通过提供的功能调用获取信息，如果没有获取到信息，则回复\"我不知道\"").build();
        Message message = Message.builder().role(Message.Role.USER).content("本月25号成都天气如何？").build();

        //属性一
        JSONObject wordLength = new JSONObject();
        wordLength.putOpt("type", "string");
        wordLength.putOpt("description", "日期，格式为yyyy-MM-dd");
        //属性二
        JSONObject language = new JSONObject();
        language.putOpt("type", "string");
        language.putOpt("description", "所在城市");
        //参数
        JSONObject properties = new JSONObject();
        properties.putOpt("date", wordLength);
        properties.putOpt("city", language);
        Parameters parameters = Parameters.builder()
                .type("object")
                .properties(properties)
                .required(Arrays.asList("name", "day")).build();
        Functions functions = Functions.builder()
                .name("search_w")
                .description("根据日期获取所在城市的天气信息")
                .parameters(parameters)
                .build();

        Functions functionsDate = Functions.builder()
                .name("search_date")
                .description("获取当前时间")
                .build();
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .messages(Arrays.asList(sysMessage, message))
                .functions(Arrays.asList(functions,functionsDate))
                .functionCall("auto")
                .temperature(0.2f)
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .build();
        ChatCompletionResponse chatCompletionResponse = client.chatCompletion(chatCompletion);

        chatCompletionResponse.getChoices().forEach(e -> {
            System.out.println(e.getFinishReason());
            System.out.println(e.getMessage().getFunctionCall());
        });
//        client.chatCompletion(chatCompletion);
//       // client.streamChatCompletion(chatCompletion, eventSourceListener);
//        CountDownLatch countDownLatch = new CountDownLatch(1);
//        try {
//            countDownLatch.await();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }

    public static void test1() {
        OpenAiLlmConfig config = new OpenAiLlmConfig();
        config.setApiKey("sk-rts5NF6n*******");

        Llm llm = new OpenAiLlm(config);

        String prompt = "Please write a story about a little rabbit defeating a big bad wolf";
        llm.chat(new SimplePrompt(prompt), (llmInstance, message) -> {
            System.out.println("--->" + message.getContent());
        });
    }

    public static String embedding(String... input) {
        String url = BASE_URL + "embeddings";
        Map<String, Object> param = new HashMap<>();
        param.put("model", embeddingModel);//"text-embedding-ada-002");
        param.put("encoding_format", "float");
        param.put("input", input);
        String ret = HttpUtil.createPost(url)
                .auth("Bearer " + apiKey)
                .contentType("application/json")
                .body(JSONUtil.toJSONString(param)).execute().body();
        return ret;
    }

    public static void speech(String text) throws FileNotFoundException {
        String url = BASE_URL + "audio/speech";
        Map<String, Object> param = new HashMap<>();
        param.put("model", "tts-1");
        param.put("input", text);
        param.put("voice", "shimmer");
        HttpUtil.createPost(url)
                .auth("Bearer " + apiKey)
                .contentType("application/json")
                .body(JSONUtil.toJSONString(param)).execute().writeBody("./output.mp3");
        System.out.println("success");

    }
//    public static String completions(String model,String history,String ...input){
//
//    }
}
*/
